import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/config/address.dart';
import 'package:xvideos/extension/date_string_extension.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/online_pay_page.dart';
import 'package:xvideos/hj_page/web_page/h5_page.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/tools_base/net/net_manager.dart';
import 'package:xvideos/tools_base/widget/net_image_widget.dart';

import '../../hj_model/splash/domain_source_model.dart';
import '../../hj_model/video_model.dart';
import '../../tools_base/debug_log.dart';
import '../mine_business/mine_vip/vip_support_model.dart';
import 'pre_sale_alert.dart';
import 'pre_sale_model.dart';
import 'pre_sale_service.dart';

extension providerTime on String? {
  /// 当前时间与特定时间差值
  /// < 0 当前时间没有到达特定时间 > 0 当前时间已经过了特定时间
  int calculateDiffDateByBeforeDate() {
    if (this == null) return -1;
    if (this!.isEmpty || this!.contains('0001-01-01')) return -1;
    final beforD = DateTime.parse(this!).toLocal();
    final diff = DateTime.now().difference(beforD);
    return diff.inSeconds;
  }

  String formartPaybalanceByDate() {
    if (this == null) return '';
    if (this!.isEmpty || this!.contains('0001-01-01')) return '';
    var time = DateTime.parse(this!).toLocal();
    //计算时间差
    var difference = time.difference(DateTime.now());

    String day = difference.inDays.toString();
    var hours = (difference.inHours % 24);
    var minutes = (difference.inMinutes % 60);
    var second = (difference.inSeconds % 60);
    return "$day天 "
        "${hours < 10 ? "0$hours" : hours}:"
        "${minutes < 10 ? "0$minutes" : minutes}:"
        "${second < 10 ? "0$second" : second}";
  }

  ///  当前特定时间与当前时间差值
  /// < 0 当前时间没有到达 特定时间 > 0 当前时间已经过了特定时间
  int calculateDiffDateByAfterDate() {
    if (this == null) return -1;
    if (this!.isEmpty || this!.contains('0001-01-01')) return -1;
    final afterD = DateTime.parse(this!).toLocal();
    final diff = afterD.difference(DateTime.now());
    return diff.inSeconds;
  }
}

final presaleProvider = PreSaleProvider();

class PreSaleProvider extends ChangeNotifier {
  static final PreSaleProvider _instance = PreSaleProvider._();

  PreSaleProvider._();

  factory PreSaleProvider() => _instance;
  Timer? _timer;

  String? luckyDrawH5; //限时活动抽奖h5
  String? luckyDrawIcon; //限时活动icon配置

  PreSaleModel? preSaleModel; // 预售活动
  AdvanceStatus? advanceStatus; // 预售状态
  AdvancePage? advancePage; //预售页面资源

  bool isPayAll() => preSaleModel?.detailModel?.status == 4; // 是否支付完首尾款

  bool isPayFirst() => (preSaleModel?.detailModel?.status == 2 || preSaleModel?.detailModel?.status == 3); //支付首款未付尾款

  bool get balancePayment => preSaleModel?.detailModel?.balancePayment ?? false; //是否有尾款支付

  ValueNotifier<String> deadline = ValueNotifier(''); // 付尾款截止时间倒计时

  bool get isOpen => advanceStatus?.activityStatus == true; //活动是否开启

  bool get hasLimit => advanceStatus?.privilegeLimit?.hasLimit ?? false; //是否有权益限制

  Remain? get remain => advanceStatus?.privilegeLimit?.remain; //剩余权限次数

  // 金币视频免费观看权益次数
  int get coinVideoFreeCount {
    if (hasLimit == false) return -1; //没有权益
    if (isOpen && !isPayAll()) {
      //有首款权益，判断当前免费权益金币视频数量
      if ((remain?.todayCoinVideoCount ?? -1) >= 0) {
        // ⚠️注意业务层判断: 大等于0 是有权益的, (如只有一次,即count =1 ,业务层先减权益数即count = 0,再做其他的逻辑, 是先减)
        return remain!.todayCoinVideoCount!;
      }
    }
    return -1;
  }

// 是否可以支付尾款
  bool canPayBalance() {
    return (isPayFirst() && (preSaleModel?.detailModel?.startTime?.calculateDiffDateByBeforeDate() ?? -1) > 0);
  }

  /// 截止时间的差值
  int calculateDiffToEnd() {
    return preSaleModel?.detailModel?.endTime?.calculateDiffDateByAfterDate() ?? -1;
  }

  //刷新相关接口
  Future<void> refreshPreSaleData() async {
    refreshPreSaleConfig();
    refreshPreSalStatus();
  }

  /// 预售配置相关数据
  Future<void> refreshPreSaleConfig() async {
    final res = await PreSaleService.fetchPresaleConfigAndVideos();
    preSaleModel = res;
    // 如果开始支付尾款了 开启定时器 全局通用的
    if (canPayBalance() && (calculateDiffToEnd() > 0)) {
      if (_timer == null) {
        _startTimer();
      }
    }
    notifyListeners();
  }

  /// 预售配置相关状态
  Future<void> refreshPreSalStatus() async {
    AdvanceStatus? res = await PreSaleService.fetchAdvanceStatus();
    if (res != null) {
      advanceStatus = res;
      notifyListeners();
    }
  }

  //是否展示预售入口
  bool presaleEnterNeedShow() {
    if (!isOpen || isPayAll() || calculateDiffToEnd() < 0) {
      return false;
    }
    return true;
  }

  /// 定时器
  _startTimer() {
    Timer.periodic(Duration(seconds: 1), (timer) {
      deadline.value = preSaleModel?.detailModel?.endTime?.formartPaybalanceByDate() ?? '';
      if (calculateDiffToEnd() < 0) {
        timer.cancel();
        _timer = null;
        notifyListeners();
      }
    });
  }

  //金币视频
  todayCoinReduce() {
    presaleProvider.remain?.todayCoinVideoCount = (presaleProvider.remain?.todayCoinVideoCount ?? 0) - 1;
    notifyListeners();
  }

  //今日下载
  todayDownloadReduce() {
    presaleProvider.remain?.todayDownloadCount = (presaleProvider.remain?.todayDownloadCount ?? 0) - 1;
    notifyListeners();
  }

  //ai脱衣
  todayAIReduce() {
    presaleProvider.remain?.todayAiUndressCount = (presaleProvider.remain?.todayAiUndressCount ?? 0) - 1;
    notifyListeners();
  }

  //预售弹窗逻辑
  showPreSaleAlert() async {
    final canPop = advanceStatus?.activityPopUp ?? false;
    if (!canPop) return;
    if (preSaleModel == null) return;
    final status = preSaleModel?.detailModel?.status ?? -1;
    final payBalance = balancePayment;
    // 未知或者已经完成
    if (status == -1 || status == 4) return;
    if (!payBalance) {
      //1.预定弹窗
      await Get.dialog(PreSaleBookingAlert());
      return;
    }
    //2.支付尾款
    if (canPayBalance()) await Get.dialog(PreSaleBalancePayAlert());
  }

  //预售弹窗逻辑
  bool showPreSaleEnter() {
    final canPop = advanceStatus?.activityPopUp ?? false;
    if (!canPop) return false;
    if (preSaleModel == null) return false;
    final status = preSaleModel?.detailModel?.status ?? -1;
    final payBalance = balancePayment;
    // 未知或者已经完成
    if (status == -1 || status == 4) return false;
    if (!payBalance) {
      return true;
    }
    //2.支付尾款
    return true;
  }

  // 支付按钮样式
  String generatePayButtonTitle() {
    if (balancePayment == false) return advancePage?.buttonBackground ?? '';
    if ((preSaleModel?.detailModel?.startTime?.calculateDiffDateByBeforeDate() ?? -1) > 0)
      return advancePage?.buttonProcBackground ?? '';
    return advancePage?.buttonWaitBackground ?? '';
  }

  //预售小图标入口
  String generatePayEnterButton() {
    final imageUrl = balancePayment
        ? canPayBalance()
            // 开启支付尾款
            ? advancePage?.enterBgProc ?? ''
            : advancePage?.enterBgProc ?? ''
        // 开启预定
        : advancePage?.enterBgWait ?? '';
    return imageUrl;
  }

  //预售banner
  String generatePayBanner() {
    final imageUrl = balancePayment
        ? canPayBalance()
            // 开启支付尾款
            ? advancePage?.bannerProc ?? ''
            : advancePage?.bannerWait ?? ''
        // 开启预定
        : advancePage?.banner ?? '';
    return imageUrl;
  }

  //预售权益金币购买弹窗底部提示
  benefitsTips() {
    if (canPayBalance()) {
      return ValueListenableBuilder(
          valueListenable: deadline,
          builder: (BuildContext context, dynamic value, Widget? child) {
            return Container(
              padding: EdgeInsets.only(top: 11),
              alignment: Alignment.center,
              child: Text(
                '仅剩 $value',
                style: TextStyle(color: Color(0xff22BB9C), fontSize: 12),
              ),
            );
          });
    } else if (isPayFirst() && (preSaleModel?.detailModel?.startTime.calculateDiffDateByBeforeDate() ?? -1) <= 0) {
      return Container(
        padding: EdgeInsets.only(top: 11),
        alignment: Alignment.center,
        child: Text(
          '${preSaleModel?.detailModel?.startTime?.utcTimeToChineseMDString()} 限时开启',
          style: TextStyle(color: Color(0xffFFCC14), fontSize: 12),
        ),
      );
    } else {
      return SizedBox.shrink();
    }
  }

  bool get isNeedShowTime {
    if (canPayBalance()) {
      return true;
    } else if (isPayFirst() && (preSaleModel?.detailModel?.startTime.calculateDiffDateByBeforeDate() ?? -1) <= 0) {
      return true;
    } else {
      return false;
    }
  }

  //跳转h5抽奖
  gotoLuckydraw() async {
    if (presaleProvider.luckyDrawH5?.isNotEmpty == true) {
      final token = await netManager.getToken();
      String url = "${presaleProvider.luckyDrawH5}&token=$token&appUrl=${Address.baseHost}";
      print('gotoLuckydraw == $url');
      Get.to(
        H5Page(url: url, showAppbar: false),
        opaque: false,
      );
    }
  }

  // 拉起支付
  onInitiatePayAction(VipProductModel model) {
    if (isPayFirst() && (preSaleModel?.detailModel?.startTime.calculateDiffDateByBeforeDate() ?? -1) <= 0) {
      showToast("还未到尾款支付时间，无法支付~");
      return;
    }
    if (calculateDiffToEnd() <= 0) {
      showToast("已超过预定支付时间，无法支付~");
      return;
    }
    Get.bottomSheet(OnlinePayPage(vipProductModel: model..isPreSale = true), isScrollControlled: true);
  }

  //免费看金币视频次数(权益) 消费
  Future consumeVCoinPrivilegeCount(VideoModel? videoModel) async {
    if (videoModel?.videoType == 1) return; // 动漫视频不享受金币权益
    if (videoModel?.freeArea == true) return;
    if (videoModel?.isCoinVideo() == true && (videoModel?.coins ?? 0) > 0 && videoModel?.vidStatus?.hasPaid != true) {
      if (presaleProvider.isOpen && !presaleProvider.isPayAll()) {
        if (presaleProvider.hasLimit == false) return; //没有权益
        //有首款权益，判断当前免费权益金币视频数量
        if ((presaleProvider.remain?.todayCoinVideoCount ?? 0) > 0) {
          presaleProvider.remain?.reduceVideoCoinCount();
          final resp = await PreSaleService.consumePrivilege(privilegeType: 'coinVideo');
          if (resp.isSuccess) {
            debugLog("权益次数消费成功: ${presaleProvider.remain?.todayCoinVideoCount}");
          }
        } else {
          presaleProvider.remain?.reduceVideoCoinCount();
        }
      }
    }
  }
}

//活动抽奖
class LuckyDrawButton extends StatelessWidget {
  final EdgeInsetsGeometry? margin;

  const LuckyDrawButton({super.key, this.margin});

  @override
  Widget build(BuildContext context) {
    return presaleProvider.luckyDrawH5?.isNotEmpty == true
        ? Container(
            margin: margin,
            child: InkWell(
              onTap: () async {
                presaleProvider.gotoLuckydraw();
              },
              child: presaleProvider.luckyDrawIcon?.isNotEmpty == true
                  ? NetworkImageLoader(
                      imageUrl: presaleProvider.luckyDrawIcon ?? '',
                      width: 60,
                      height: 60,
                    )
                  : Image.asset('lucky_lottery.gif'.commonImgPath, width: 60),
            ),
          )
        : SizedBox();
  }
}
